package com.wg.springboot.thread;

import cn.hutool.extra.spring.SpringUtil;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @Description: 全局线程池
 * @Author WuGang
 * @Date 2022/7/22 13:54
 * @Version 1.0
 */
//spring是一个大容器池，把这个类bean放进去
@Component
public class ThreadPoolConfig {
    //    或者声明一个属性，下面方法set线程池对象到这个属性，用的时候注入这个类

    @Primary  //这个注解多个相同bean的时候这个是主要的
//    方法名为bean的名字，把这个方法的返回对象放到大容器池，并覆盖源码空的相同的类的bean
    @Bean
    public ThreadPoolExecutor initThread() {
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(5,
                200,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        return executorService;
    }

//    如何使用全局线程池两种方式

    @Autowired
    ThreadPoolExecutor executorService1;

    @Test
    public void test05() throws ExecutionException, InterruptedException, TimeoutException {
        ThreadPoolExecutor executorService = SpringUtil.getBean("initThread");
    }
}
